<template>
  <div>
    <a-drawer
      :title="titleMap"
      :width="980"
      :visible.sync="visible"
      :body-style="{ 'padding-top': '0px', paddingBottom: '80px' }"
      @close="close"
    >
      <a-form :form="form" layout="vertical">
        <div>
          <!-- 注册识别风险 -->
          <a-form-item
            style="margin: 0"
            :label="$t('user.verification-code.required111566125')"
          >
            <a-input
              v-decorator="[
                'RiskName',
                {
                  rules: [
                    {
                      required: true,
                      message: $t(
                        '222user.verification-code.required11156612511'
                      ),
                    },
                  ],
                },
              ]"
              :placeholder="$t('user.verification-code.required11156612511')"
              style="width: 900px"
              :disabled="disabled"
            />
          </a-form-item>
          <a-form-item
            style="margin: 0"
            :label="$t('user.verification-code.required111566153')"
          >
            <a-textarea
              :auto-size="{ minRows: 3, maxRows: 10 }"
              :placeholder="$t('user.verification-code.required111566154')"
              :rows="3"
              v-decorator="[
                'RiskDetail',
                {
                  rules: [
                    {
                      required: true,
                      message: $t(
                        'user.verification-code.required111566110577353'
                      ),
                    },
                  ],
                },
              ]"
              style="width: 900px"
              :disabled="disabled"
            />
          </a-form-item>
          <a-row>
            <!-- 时间组合 -->
            <a-col :span="12">
              <a-form-item
                :label="$t('user.verification-code.required111566155')"
              >
                <a-date-picker
                  v-decorator="[
                    'RiskStartTime',
                    {
                      rules: [
                        {
                          type: 'object',
                          required: true,
                          message: this.$t(
                            'user.verification-code.required111566110577285'
                          ),
                        },
                      ],
                    },
                  ]"
                  format="YYYY-MM-DD"
                  style="width: 440px"
                  :disabled-date="disabledDate"
                  :disabled="disabled"
                  @change="updateRiskDeadline"
                  :placeholder="$t('user.verification-code.required111566157')"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                :label="$t('user.verification-code.required111566156')"
              >
                <a-date-picker
                  v-decorator="[
                    'RiskDeadline',
                    {
                      rules: [
                        {
                          type: 'object',
                          required: true,
                          message: this.$t(
                            'user.verification-code.required111566110577285'
                          ),
                        },
                      ],
                    },
                  ]"
                  format="YYYY-MM-DD"
                  style="width: 440px"
                  :disabled="disabled"
                  :disabled-date="disabledDateDeadline"
                  :placeholder="$t('user.verification-code.required111566157')"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <!-- 对象组合 -->
            <a-col :span="12">
              <a-form-item
                :label="$t('user.verification-code.required111566128')"
                :colon="false"
                labelAlgin="left"
              >
                <a-select
                  v-decorator="[
                    'RiskOwnerUserId',
                    {
                      rules: [
                        {
                          required: true,
                          message: $t(
                            'user.verification-code.required111566110577371442281431999'
                          ),
                        },
                      ],
                    },
                  ]"
                  :placeholder="
                    $t('user.verification-code.required11156612811')
                  "
                  show-search
                  :default-active-first-option="false"
                  v-model="inputValue"
                  @search="filte1rOption"
                  :showArrow="false"
                  :filterOption="false"
                  style="width: 440px"
                  :disabled="disabled"
                >
                  <a-select-option
                    v-for="item in userList"
                    :value="item.value"
                    :key="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                :label="$t('user.verification-code.required111566159')"
                :colon="false"
                labelAlgin="left"
              >
                <a-select
                  v-decorator="[
                    'RiskDcoUserId',
                    {
                      rules: [
                        {
                          required: true,
                          message: $t(
                            'user.verification-code.required111566110577371442281431888'
                          ),
                        },
                      ],
                    },
                  ]"
                  :placeholder="
                    $t('user.verification-code.required11156615911')
                  "
                  style="width: 440px"
                  show-search
                  option-filter-prop="children"
                  :filter-option="filterOption"
                  :disabled="disabled"
                >
                  <a-select-option
                    v-for="item in userDCOList"
                    :value="item.value"
                    :key="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <!-- 风险组合 -->
            <a-col :span="12">
              <a-form-item
                :label="$t('user.verification-code.required111566160')"
                :colon="false"
              >
                <a-select
                  v-decorator="[
                    'RiskLevel',
                    {
                      rules: [
                        {
                          required: true,
                          message: $t(
                            'user.verification-code.required111566110577356'
                          ),
                        },
                      ],
                    },
                  ]"
                  :placeholder="
                    $t('user.verification-code.required11156616011')
                  "
                  style="width: 440px"
                  :disabled="disabled"
                  option-filter-prop="children"
                  :filter-option="filterOption"
                  show-search
                >
                  <a-select-option
                    v-for="item in riskLevel"
                    :value="item.value"
                    :key="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <!-- 风险类型 -->
              <a-form-item
                :label="$t('user.verification-code.required111566161')"
                :colon="false"
              >
                <a-select
                  v-decorator="[
                    'RiskType',
                    {
                      rules: [
                        {
                          required: true,
                          message: $t(
                            'user.verification-code.required111566110577357'
                          ),
                        },
                      ],
                    },
                  ]"
                  option-filter-prop="children"
                  :filter-option="filterOption"
                  show-search
                  :placeholder="
                    $t('user.verification-code.required11156616111')
                  "
                  style="width: 440px"
                  :disabled="disabled"
                >
                  <a-select-option
                    v-for="item in riskType"
                    :value="item.value"
                    :key="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <!-- 风险备注 -->
          <a-form-item :label="$t('user.verification-code.required111566162')">
            <a-textarea
              v-decorator="[
                'RiskRemark',
                {
                  rules: [
                    {
                      required: true,
                      message: $t(
                        'user.verification-code.required111566110577358'
                      ),
                    },
                  ],
                },
              ]"
              :placeholder="$t('user.verification-code.required111566162')"
              :rows="4"
              style="width: 900px"
              :disabled="disabled"
            />
          </a-form-item>
          <!-- 风险处置计划描述 -->
          <a-form-item :label="$t('user.verification-code.required111566183')">
            <a-textarea
              v-decorator="['RiskDisposeDetail']"
              :placeholder="$t('user.verification-code.required11156618311')"
              :rows="4"
            />
          </a-form-item>
          <a-form-item label="ID" v-if="mode == 1" class="hidden">
            <a-input v-decorator="['id']" />
          </a-form-item>
          <!-- 上传提交 -->
        </div>
        <div
          class="absolute right-0 bottom-0 w-full px-4 py-[10px] bg-white text-left z-1 flex justify-center"
        >
          <!-- 提交时 -->
          <a-row class="w-full" :gutter="24">
            <a-col :span="12">
              <a-button
                :loading="loading"
                class="w-full border-none shadow"
                type="primary"
                @click.native.prevent="submit('add')"
              >
                <span v-if="!loading">{{
                  $t("user.verification-code.required111566165")
                }}</span>
                <span v-else>{{ $t("app.setting.themecolor.tt") }}...</span>
              </a-button>
            </a-col>
            <a-col :span="12">
              <a-button
                :loading="loading"
                class="w-full border-none shadow"
                type="primary"
                @click.native.prevent="submit('edit')"
              >
                <span v-if="!loading">{{
                  $t("user.register-result.view-mailbox")
                }}</span>
                <span v-else>{{ $t("app.setting.themecolor.tt") }}...</span>
              </a-button>
            </a-col>
          </a-row>
        </div>
      </a-form>
    </a-drawer>
  </div>
</template>

<script>
import storage from "store";
import { riskCreate } from "@/api/risk/json";
import {
  delRiskFile,
  RISKActionList,
  RISKEditActionList,
  ristCreateAction,
  ristDelAction,
} from "@/api/risk/form";
import moment from "moment";
import creatRiskAction from "./creatRiskAction.vue";
import success from "@/views/risk/components/success.vue";
import axios from "axios";
import { DcoQuery, getUserList } from "@/api/common/form";
import { ACCESS_TOKEN } from "@/store/mutation-types";

const data = [];

export default {
  components: {
    creatRiskAction,
    success,
  },
  props: {
    riskLevel: {
      type: Array,
    },
    riskType: {
      type: Array,
    },
    editId: {
      type: Number,
    },
  },
  data() {
    return {
      disabled: false,
      listLoading: false,
      data,
      listData: [],
      //编辑的截止时间
      RiskDeadline: "",
      headers: {
        authorization: "authorization-text",
      },
      // 下面这些都是通的
      form: this.$form.createForm(this),
      visible: false,
      userDCOList: [],
      //审阅抽屉显示
      reviewVisible: false,
      loading: false,
      // 这个要根据服务修改title
      // titleMap: ['新增风险', '修改风险'],
      titleMap: "",
      mode: 0,
      //risk主页面编辑id
      riskEditId: null,
      current: 0,
      // 时间配置
      config: {
        rules: [
          {
            type: "object",
            required: true,
            message: this.$t("user.verification-code.required111566110577285"),
          },
        ],
      },
      // 分页参数
      pagination: {
        page: 1, //当前页
        pageSize: 10, //每页条数
        total: 0, //总条数
        showQuickJumper: true,
        hideOnSinglePage: true,
      },
      submitId: "0",
      env: process.env.VUE_APP_BASE_API,
      //存上传文件接口地址
      urlList: [],
      //点新建时的风险Id
      riskId: null,
      //选择的riskAction列表ID
      RiskListSelectId: null,
      fileLists: [],
      userList: [],
      timerId: "",
      keyword: "",
      inputValue: "",
    };
  },

  computed: {
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          this.RiskListSelectId = [selectedRowKeys].join("");
        },
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.name === "Disabled User", // Column configuration not to be checked
            name: record.name,
          },
        }),
      };
    },
  },
  watch: {
    async inputValue(value) {
      const { data } = await getUserList({ UserEmail: value, UserName: value });
      this.userList = data;
    },
  },
  methods: {
    /**
     *
     * @param {*} type 0 新增 1 修改
     * @param {*} data 列表传过来的值
     */
    async open(mode, data = {}, editId) {
      this.mode = mode;
      this.userList = [];
      if (mode === 0) {
        this.titleMap = this.$t(
          "user.verification-code.required111566110577146"
        );
        this.mode = mode;
        this.visible = true;
        const res = await riskCreate();
        this.riskId = res.data.Id;
        await this.getList(this.riskId);
      }
      // 如果是修改
      else {
        this.userList.push({
          value: data.RiskOwnerUserId,
          label: data.RiskOwnerUserName,
        });
        this.titleMap = this.$t(
          "user.verification-code.required111566110577147"
        );
        this.riskData = data;
        this.riskEditId = data.Id;
        this.RiskDeadline = data.RiskDeadline;
        this.visible = true;
        await this.getList(data.Id);
        await this.$nextTick();
        //修改的时候需要给form赋值
        this.form.setFieldsValue({
          RiskName: data.RiskName,
          RiskDetail: data.RiskDetail,
          RiskOwnerUserId: data.RiskOwnerUserId
            ? data.RiskOwnerUserId
            : undefined,
          RiskLevel: data.RiskLevel === 0 ? undefined : data.RiskLevel,
          RiskStartTime: data.RiskStartTime
            ? moment(data.RiskStartTime, "YYYY-MM-DD HH:mm:ss")
            : null,
          RiskType: data.RiskType === 0 ? undefined : data.RiskType,
          RiskDcoUserId:
            data.RiskDcoUserId === "-"
              ? undefined
              : parseInt(data.RiskDcoUserId),
          RiskDeadline: data.RiskDeadline
            ? moment(data.RiskDeadline, "YYYY-MM-DD HH:mm:ss")
            : null,
          RiskRemark: data.RiskRemark,
          RiskDisposeDetail: data.RiskDisposeDetail,
        });
        if (data.File) {
          data.File.forEach((item, index) => {
            let name = item.RiskUploadUrl.split("/");
            console.log(item);
            this.fileLists.push({
              uid: index,
              name: name[name.length - 1],
              status: "done",
              url: item.RiskUploadUrl,
              RiskUploadType: 1,
              fileId: item.Id,
            });
          });
        }
        this.mode = mode;
      }
    },
    async filte1rOption(value) {
      this.inputValue = value;
    },

    //开始时间
    disabledDate(current) {
      const currentDate = moment().format("YYYY-MM-DD");
      return current && current.format("YYYY-MM-DD") < currentDate;
    },
    //截止时间
    updateRiskDeadline() {
      const riskStartTime = this.form.getFieldValue("RiskStartTime");
      const riskDeadline = this.form.getFieldValue("RiskDeadline");
      if (riskStartTime && riskDeadline && riskStartTime > riskDeadline) {
        this.form.setFieldsValue({
          RiskDeadline: riskStartTime,
        });
      }
    },

    disabledDateDeadline(current) {
      const riskStartTime = this.form
        .getFieldValue("RiskStartTime")
        .format("YYYY-MM-DD");
      return current && current.format("YYYY-MM-DD") < riskStartTime;
    },
    async getList(id) {
      this.listLoading = true;
      const { page, pageSize } = this.pagination;
      try {
        //审批人DCO
        // 获取用户列表下拉
        const { data: userList } = await DcoQuery({ ApprovalAlias: "DCO" });
        this.userDCOList = userList;
        // 调用查询列表
        const { data } = await RISKActionList({
          ...{ page, pageSize },
          ...this.queryForm,
          RiskId: id,
        });
        // 解构赋值
        const { Page, PageSize, Total, Lists } = data;
        // 给table赋值
        this.listData = Lists || [];

        // 给分页数据赋值
        this.pagination = {
          page: Page,
          pageSize: PageSize,
          total: Total,
        };
      } catch (error) {
        // 报错信息
        this.$message.error(error);
      } finally {
        // 不管成功失败都会执行
        this.listLoading = false;
      }
    },
    // 上传提交
    //文件上传
    async handleChange(e) {
      // 上传提交
      this.uploadLoading = true;
      let formdata = new FormData();
      formdata.append("file", e.file);
      try {
        const { status, data } = await axios({
          url: `${this.env}/v1/oss/upload`,
          method: "post",
          data: formdata,
          headers: {
            token: storage.get(ACCESS_TOKEN),
            tokens: storage.get("bmwToken") || "",
          },
        });
        if (status === 200 && data.code === 1) {
          if (data.data !== "") {
            await this.$nextTick();
            var files = data.data;
            var index = this.fileLists.length;
            if (files !== "" && files !== undefined) {
              var fileName = files.split("/");
              console.log(data);
              this.fileLists.push({
                uid: index + 1,
                name: fileName[fileName.length - 1],
                status: "done",
                url: data.Url + data.data,
                fileId: data.Id,
              });
              // 上传文件完成后新增
              // 新增
              this.mode === 0
                ? this.urlList.push({
                    RiskUploadType: 1,
                    RiskId: this.riskId,
                    RiskUploadUrl: data.data,
                  })
                : this.urlList.push({
                    RiskUploadType: 1,
                    RiskId: this.riskEditId,
                    RiskUploadUrl: data.data,
                  });
            }
          }
        } else {
          this.$message.error(
            this.$t("user.verification-code.required111566110577282")
          );
        }
      } catch (error) {
        this.$message.error(error);
      } finally {
        this.uploadLoading = false;
      }
    },
    //删除上传文件
    async delFile(file) {
      const index = this.fileLists.indexOf(file);
      this.fileLists.splice(index, 1);
      await delRiskFile({ Id: file.fileId });
      return true;
    },
    previousPage() {
      this.current--;
    },
    nextPage() {
      const {
        form: { validateFields },
      } = this;
      validateFields({ fore: true }, async (err, values) => {
        try {
          if (!err) {
            this.current++;
          }
        } catch (error) {
          this.$message.error(error);
        } finally {
          this.loading = false;
        }
      });
    },
    // 提交 通用的
    submit(type) {
      console.log(this.mode);
      const {
        form: { validateFields },
      } = this;
      // 按钮loading
      this.loading = true;
      // validateFields 是校验form表单数据
      // force: true 是默认所有字段都校验
      // values 表单的值
      validateFields({ force: true }, async (err, values) => {
        const RiskStartTime = moment(values["RiskStartTime"]).format(
          "YYYY-MM-DD"
        );
        values["RiskStartTime"] = RiskStartTime;
        const RiskDeadline = moment(values["RiskDeadline"]).format(
          "YYYY-MM-DD"
        );
        values["RiskDeadline"] = RiskDeadline;
        const urlList = this.urlList;
        values["File"] = urlList;
        if (type === "add") {
          values["RiskState"] = 2;
        } else {
          values["RiskState"] = 1;
        }
        if (!err) {
          for (var arr = 0; arr < this.userList.length; arr++) {
            if (this.userList[arr].value === values.RiskOwnerUserId) {
              values.RiskOwnerUserName = this.userList[arr].label;
            }
          }
          for (var arr = 0; arr < this.userDCOList.length; arr++) {
            if (this.userDCOList[arr].value === values.RiskDcoUserId) {
              values.RiskDcoUserName = this.userDCOList[arr].label;
            }
          }

          try {
            if (this.mode === 0) {
              console.log("新增");
              values["Id"] = this.riskId;
              const { data } = await riskCreate(values);
              // const { data1 } = await RiskListSelect({ riskId: this.riskId, ids: this.RiskListSelectId })
            } else {
              console.log();
              console.log("编辑");
              console.log(this.riskEditId);
              values["Id"] = this.riskEditId;
              const { data } = await riskCreate(values);
              // const { data1 } = await RiskListSelect({ riskId: this.editId, ids: this.RiskListSelectId })
            }
            // 如果成功就调用父页面当前组件的succeed上绑定的事件
            this.$emit("succeed");
            this.$message.success(
              this.$t("user.verification-code.required111566110577308")
            );
            this.close();
            //如果成功就关闭
            this.current++;
          } catch (error) {
            this.$message.error(error);
          } finally {
            this.loading = false;
          }
        } else {
          setTimeout(() => {
            this.loading = false;
          }, 600);
        }
      });
    },
    async showModal(state, editId) {
      if (state === "0") {
        //新建时获取action ID
        const { data } = await ristCreateAction();
        this.$refs.creatRiskAction.openAction(editId, data, state);
      } else {
        //编辑
        try {
          const { data } = await RISKEditActionList({ Id: editId });
          //传值回显
          this.$refs.creatRiskAction.openAction(editId, data);
        } catch (error) {
          // 报错信息
          this.$message.error(error);
        } finally {
          // 不管成功失败都会执行
          this.listLoading = false;
        }
      }
    },
    // 删除
    async del(record) {
      this.listLoading = true;
      try {
        console.log(record);
        await ristDelAction({ Id: record.Id });
        this.$message.success(
          this.$t("user.verification-code.required111566110577133")
        );
        this.getList(record.RiskId);
      } catch (error) {
        // 报错信息
        this.$message.error(error);
      } finally {
        // 不管成功失败都会执行
        this.listLoading = false;
      }
    },
    // 关闭 通用的
    close() {
      const {
        form: { validateFields },
      } = this;
      validateFields({ fore: true }, async (err, values) => {
        try {
          if (
            (this.mode != 2 && this.current == 1) ||
            (this.mode != 2 && this.current == 0)
          ) {
            this.$emit("data-updated", this.riskId);
            console.log("this.riskId", this.riskId);
          }
        } catch (error) {
          console.log("err", error);
          this.$message.error(error);
        } finally {
          this.loading = false;
        }
      });
      this.riskId = null;
      this.fileLists = [];
      this.urlList = [];
      this.$emit("initEditId");
      this.mode = "0";
      this.current = 0;
      this.$emit("getList");
      console.log("触发了");
      this.disabled = false;
      // 修改侧边栏状态
      this.visible = false;
      this.reviewVisible = false;
      // 清空form的值
      this.form.resetFields();
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>
<style lang="less" scoped>
.drawerHeader {
  margin: 20px;
}

.ant-pagination {
  float: right;
  padding-bottom: 60px;
}
</style>